<template>
  <div class="collaborationLedger">
     <PageTitle :goBack="false" title="内部采购价格库" :border="true" />
    <div class="info-div">
      <a-tabs v-model:activeKey="activeKey" @change="changeKey">
        <a-tab-pane :key="item.id" :tab="item.name" v-for="item in tabList"></a-tab-pane>
      </a-tabs>
    </div>
    <div class="myCardCss" style="width: 100%">
      <div class="searchDiv">
        <div>
          <div class="search-box" v-for="(item, index) in searchList" :key="index">
            <a-select
              v-model:value="item.field"
              placeholder="字段名称"
              allow-clear
              style="width: 180px; margin-right: 8px"
              @change="changeZd($event, index)"
            >
              <a-select-option :value="itemchild.value" v-for="(itemchild, itemindex) in zdList" :key="itemindex">{{itemchild.label}}</a-select-option>
            </a-select>
            <a-select
              v-model:value="item.operator"
              placeholder="判断条件"
              allow-clear
              style="width: 150px; margin-right: 8px"
            >
              <a-select-option :value="itemchild.value" v-for="(itemchild, itemindex) in item.tjList" :key="itemindex">{{itemchild.label}}</a-select-option>
            </a-select>
            <a-date-picker v-if="item.format === 'datetime' && !['is_null', 'is_not_null'].includes(item.operator)" v-model:value="item.values" valueFormat="YYYY-MM-DD"/>
            <a-input
              v-if="item.format !== 'datatime' && !['is_null', 'is_not_null'].includes(item.operator)"
              style="width: 180px; margin-right: 8px"
              placeholder="查询内容"
              allow-clear
              v-model:value="item.values"
            >
            </a-input>
            <label v-if="!index" style="color: #1473dc;margin-right: 12px;line-height: 30px" @click="addSearch">+ 添加条件</label>
            <label v-if="index" style="color: red;margin-right: 12px;line-height: 30px" @click="delSearch(index)">- 删除条件</label>
            <a-button
              v-if="!index"
              type="primary"
              danger
              @click="searchDataForButton"
              style="border-radius: 4px;margin-right: 12px"
            >查询</a-button
            >
            <a-button v-if="!index" @click="ressetData" style="border-radius: 4px">重置</a-button>
          </div>
        </div>
        <div class="buttons" v-if="dataSource.length">
<!--          <div class="exportBtn all-4-border" style="margin-right: 8px" @click="addLedger">-->
<!--            新增-->
<!--          </div>-->
          <a-button type="primary" style="margin-right: 8px" @click="showDialog">价格对比分析</a-button>
          <a-button class="reset-btn" @click="openUpload" style="margin-right: 12px">导入台账</a-button>
          <a-button class="reset-btn" @click="openDelBox(0)">批量删除</a-button>
        </div>
      </div>
      <a-table
        v-if="isHaveData"
        :dataSource="dataSource"
        :columns="columns"
        rowKey="id"
        :row-selection="rowSelection"
        :pagination="false"
        :scroll="{ x: 1000, y: 460 }"
        :loading="loading"
      >
        <template #index="{ index }">
          {{ (pageForm.limit - 1) * pageForm.size + index + 1 }}
        </template>
        <template #operation="{ record }">
          <a @click="openDelBox(record)" style="color: red">删除</a>
        </template>
      </a-table>
<!--      <a-pagination-->
<!--        size="small"-->
<!--        :total="pageForm.total"-->
<!--        :pageSize="pageForm.size"-->
<!--        :current="pageForm.limit"-->
<!--        :hideOnSinglePage="false"-->
<!--        :showSizeChanger="false"-->
<!--        @change="changePage"-->
<!--        style="margin-top: 30px; float: right"-->
<!--      />-->
      <!--      <div style="clear: both"></div>-->
      <div v-if="dataSource.length" class="pagination-container">
        <!-- 共有多少条 -->
        <div class="total-container">共 <span>{{ pageForm.total }}</span> 条</div>
        <a-pagination v-model:current="pageForm.limit" :total="pageForm.total" :defaultPageSize="pageForm.size" show-less-items :showSizeChanger="true" @change="changePage" @showSizeChange="changeSize" :page-size-options="pageSizeOptions"/>
      </div>
      <div class="nodata" v-if="!isHaveData">
        <label style="font-weight: bold;margin-bottom: 12px">点击导入采购台账数据</label>
        <a-button class="reset-btn" @click="openUpload">导入数据</a-button>
      </div>
    </div>
    <a-modal
      v-model:visible="isShowUpload"
      :maskClosable="false"
      :width="600"
      :centered="true"
      :okText="titleContent"
      title="批量导入"
      @ok="saveUpload"
    >
      <div class="my-upload">
        <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          :multiple="true"
          action=""
          style="height: 500px"
          :beforeUpload="handleChange"
          :remove="removeFile"
        >
          <div class="ant-upload-hint" v-if="isUploadState === 0">
            <div class="upload-icon">
              <img src="../../../assets/images/upload.png" alt="" />
            </div>
            <div class="upload-click">
              <label style="color: #1473dc">点击选择</label
              ><label>或将文件（xls、xlsx）拖拽至此上传项目表格</label>
            </div>
          </div>
          <div class="ant-upload-hint" v-if="isUploadState === 1">
            <div class="upload-icon">
              <img src="../../../assets/images/success.png" alt="" />
            </div>
            <div class="upload-click" style="color: #303133"> 上传成功 </div>
          </div>
          <div class="ant-upload-hint" v-if="isUploadState === 2">
            <div class="upload-icon">
              <img src="../../../assets/images/error.png" alt="" />
            </div>
            <div class="upload-click" style="color: #303133"> 导入失败 </div>
            <div style="color: #909399">请使用标准导入模板进行数据导入，否则将无法导入成功</div>
          </div>
        </a-upload-dragger>
      </div>
      <div class="tips">
        <div class="tipsItem"
          >· 导入的文件内容必须依照下载模板的要求填写
          <div>
            <div class="downloadBtn">
              <img src="../../../assets/images/download.png" alt="" />
              <label @click="downloadData">点击下载</label>
            </div>
          </div>
        </div>
        <div class="tipsItem">· 上传文件最大为2M，仅支持Excel表格文件（xls、xlsx）</div>
        <div class="tipsItem">· 导入重复数据将自动跳过</div>
      </div>
    </a-modal>

    <!-- 导入数据弹窗 -->
    <a-modal
      v-model:visible="isUploadDetails"
      :maskClosable="false"
      :width="1500"
      :centered="true"
      okText="完成"
      cancel-text="下载错误数据"
      title="批量导入"
      @ok="closeUploadDetails"
      @cancel="downErrorData"
      style="padding: 20px"
      :footer="false"
    >
      <div class="myTableClass">
        <div class="myHead">
          <div
            class="myCol"
            v-for="(headItem, index) in columnsByUpload"
            :key="index"
            :title="headItem"
          >
            {{ headItem }}
          </div>
        </div>
        <div class="myRow" v-for="(dataItem, index) in uploadData" :key="index">
          <div
            class="myCol"
            :class="!dataItem.valid ? 'active' : ''"
            v-for="(colItem, colIndex) in dataItem.columns"
            :key="colIndex"
            :title="colItem"
            >{{ colItem }}</div
          >
        </div>
      </div>
      <div class="footerBtn">
        <a-button @click="downErrorData" style="margin-right: 12px">下载错误数据</a-button>
        <a-button type="primary" danger @click="closeUploadDetails">完成</a-button>
      </div>
      <div style="clear: both"></div>
    </a-modal>
    <a-modal v-model:visible="isShowDelBox" title="提示" @ok="handleOk">
      <div style="padding: 20px">是否删除采购数据？</div>
    </a-modal>
    <!-- 价格对比分析 -->
    <PriceAnalysis ref="priceAnalysis" />
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import PageTitle from '/@/components/PageTitle/index.vue';
  import PriceAnalysis from './PriceAnalysis.vue';
  import { PlusCircleOutlined } from '@ant-design/icons-vue';
  import {
    deleteTableData,
    getTab,
    getTableList
  } from '/@/api/priceLibrarybyjl';
  import { getAppEnvConfig } from '/@/utils/env';
  import { downloadFiLe, downloadErrorData } from '/@/api/fileApi';
  import { checkToken } from '/@/api/checkToken';
  import { getToken } from '/@/utils/auth';
  const formRef = ref();
  let dataSource = ref([]);
  let columns = ref([
    {
      title: '序号',
      align: 'left',
      fixed: true,
      width: '80px',
      key: 'index',
      dataIndex: 'index',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: '160px',
      slots: { customRender: 'operation' },
      align: 'center',
      fixed: 'right',
    },
  ]);
  let tjList = ref([{
    label: '等于',
    value: 'eq'
  },{
    label: '不等于',
    value: 'neq'
  },{
    label: '包含',
    value: 'contains'
  },{
    label: '不包含',
    value: 'not_contains'
  },{
    label: '大于等于',
    value: 'gte'
  },{
    label: '小于等于',
    value: 'lte'
  },{
    label: '为空',
    value: 'is_null'
  },{
    label: '不为空',
    value: 'is_not_null'
  }])
  let tjListByDate = ref([{
    label: '等于',
    value: 'eq'
  },{
    label: '不等于',
    value: 'neq'
  },{
    label: '包含',
    value: 'contains'
  },{
    label: '不包含',
    value: 'not_contains'
  },{
    label: '大于等于',
    value: 'gte'
  },{
    label: '小于等于',
    value: 'lte'
  },{
    label: '为空',
    value: 'is_null'
  },{
    label: '不为空',
    value: 'is_not_null'
  }])
  let tzInfo = ref({ total: 0, counts: [] });
  let pageForm = ref({
    size: 10,
    limit: 1,
    total: 0,
  });
  let pageSizeOptions = ref(['10', '20', '30', '40', '50', '100'])
  function changePage(val) {
    pageForm.value.limit = val;
    // todo
    getData();
  }
  function changeSize(current, size) {
    pageForm.value.size = size
    getData();
  }
  let tabList = ref([])
  let activeKey = ref('')
  let downloadFileName = ref('')
  let downloadFileId = ref('')
  // 获取表格列表
  async function getTabList() {
    let queryData = {
      type: 'PROCUREMENT'
    };
    let res = await getTab(queryData)
    tabList.value = res
    if (res.length) {
      activeKey.value = res[0].id
      getZd()
      getData(1)
    }
  }
  getTabList()
  let zdList = ref([])
  function changeZd(e, index) {
    let searchItem = searchList.value[index]
    searchItem.operator = '' // 修改字段 清空条件
    searchItem.values = ''
    if (zdList.value.filter(item => e === item.value)[0].format === 'string') {
      searchItem.tjList = tjList.value
      searchItem.format = 'string'
    }
    if (zdList.value.filter(item => e === item.value)[0].format === 'datetime') {
      searchItem.tjList = tjListByDate.value
      searchItem.format = 'datetime'
    }
    searchList.value.splice(index, 1, searchItem)
    console.log(searchList.value, 2222)
  }
  // 获取字段
  async function getZd() {
    let item = tabList.value.filter(item => item.id === activeKey.value)[0]
    downloadFileName.value = item.name + '导入模板.xlsx'
    downloadFileId.value = item.tplFileId
    zdList.value = []
    item.fields.map(item => {
      if (!item.disabled) {
        zdList.value.push({
          label: item.name,
          value: item.code,
          format: item.format
        })
      }
      // return {
      //   label: item.name,
      //   value: item.code,
      //   format: item.format
      // }
    })
    columns.value = []
    item.fields.map(item => {
      if (!item.disabled) {
        columns.value.push({
          title: item.name,
          dataIndex: item.code,
          key: item.code,
          align: 'left',
          width: '100px',
        })
      }
      // return {
      //   title: item.name,
      //   dataIndex: item.code,
      //   key: item.code,
      //   align: 'left',
      //   width: '100px',
      // }
    })
    columns.value.unshift({
      title: '序号',
      align: 'center',
      slots: { customRender: 'index' },
      width: 52,
    })
    columns.value.push({
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: '160px',
      slots: { customRender: 'operation' },
      align: 'center',
      fixed: 'right',
    })
  }
  let searchList = ref([{
    field: null,
    operator: null,
    values: '',
    tjList: [],
    format: '',
  }])
  let loading = ref(false);
  let isHaveData = ref(false) // 是否有数据
  async function getData(type) {
    loading.value = true;
    let conditions = []
    searchList.value.map(item => {
      if (item.field && item.operator) {
        conditions.push({
          field: item.field,
          operator: item.operator,
          values: [item.values]
        })
      }
    })
    let queryData = {
      tableId: activeKey.value,
      conditions,
      limit: pageForm.value.limit,
      size: pageForm.value.size,
      type: 'PROCUREMENT'
    };
    const res = await getTableList(queryData);
    if (type === 1) {
      isHaveData.value = !!res.total
    }
    dataSource.value = res.list
    pageForm.value.total = res.total;
    if (!res.total && !conditions.length) {
      isHaveData.value = false
    }
    loading.value = false;
  }
  function searchData() {
    pageForm.value.limit = 1;
    getData();
  }

  /**
   * 弹出图表
   */
  const priceAnalysis = ref()
  function showDialog() {
    priceAnalysis.value.showModal(activeKey.value)
  }
  // 批量上传
  let isShowUpload = ref(false); // 是否打开批量监控弹窗
  function openUpload() {
    isShowUpload.value = true;
  }
  let fileList = ref([]) as any;
  let titleContent = ref('确定导入');
  // 下载纪录
  async function downloadData() {
    let res = await downloadFiLe(downloadFileId.value);
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download =  downloadFileName.value;
    link.href = url;
    document.body.appendChild(link);
    link.click();
  }
  let fileData = null;
  const handleChange = (file: any) => {
    fileData = file;
    fileList.value = [file];
    return false;
  };
  const removeFile = () => {
    fileList.value = [];
    fileData = null;
  };
  let isUploadState = ref(0);

  async function saveUpload() {
    if (!fileData) {
      return message.warn('请选择要上传的文件');
    }
    let action = getAppEnvConfig().VITE_GLOB_API_URL + '/table/data/import';
    const formData = new FormData();
    formData.append('file', fileData);
    formData.append('tableId', activeKey.value)
    const xhr = new XMLHttpRequest();
    xhr.open('post', action, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    xhr.onload = () => {
      const response = JSON.parse(xhr.response);
      if (response.code === 0) {
        message.success('导入成功');
        isUploadState.value = 1;
        isShowUpload.value = false;
        isHaveData.value = true
        getData();
        isUploadState.value = 0;
        fileId = response.data.errorFileId;
        errorNum = response.data.errorCount;
        uploadData.value = response.data.excelData.rows;
        columnsByUpload.value = response.data.excelData.head;
        openUploadDetails();
      }
      if (response.code === 500 || response.code === 400) {
        message.error(response.msg);
        titleContent.value = '重新上传';
        isUploadState.value = 2;
        fileData = null;
        fileList.value = [];
      }
    };
    xhr.onerror = () => {
      console.log('上传失败');
    };
    xhr.ontimeout = function timeout() {
      console.log('上传超时');
    };
    xhr.send(formData);
    fileList.value = [];
    fileData = null;
  }

  function addSearch() {
    if (searchList.value.length === 20) {
      return message.warning('筛选条件最多20个')
    }
    searchList.value.push({
      field: null,
      operator: null,
      values: '',
      tjList: [],
      format: '',
    })
  }
  function delSearch(index) {
    searchList.value.splice(index, 1)
  }
  const searchDataForButton = () => {
    getData();
  };
  function ressetData() {
    searchList.value = [{
      field: null,
      operator: null,
      values: '',
      tjList: [],
      format: '',
    }]
  }

  // 批量导入数据详情
  let isUploadDetails = ref(false);
  let uploadData = ref([]);
  let columnsByUpload = ref([]);
  let fileId = '';
  let errorNum = 0;
  // 打开窗口
  const openUploadDetails = () => {
    isUploadDetails.value = true;
  };
  // 关闭窗口
  const closeUploadDetails = () => {
    isUploadDetails.value = false;
  };
  // 下载错误数据
  const downErrorData = async () => {
    if (!errorNum) {
      message.warning('无错误数据');
      return;
    }
    let res = await downloadErrorData(fileId);
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = downloadFileName.value + '导入错误数据.xlsx';
    link.href = url;
    document.body.appendChild(link);
    link.click();
  };
  let isShowDelBox = ref(false);
  let delId = ref('');
  let selectLists = ref([])
  const openDelBox = (e: any) => {
    if (!e) {
      if (!selectLists.value.length) {
        return message.warning('请选择你要删除的数据');
      }
      delId.value = '';
    } else {
      delId.value = e.id;
    }
    isShowDelBox.value = true;
  };
  const handleOk = async () => {
    let dataIds = []
    if (delId.value) {
      dataIds = [delId.value]
    } else {
      dataIds = selectLists.value.map(item => item.id)
    }
    let queryData = {
      tableId: activeKey.value,
      dataIds
    }
    await deleteTableData(queryData);
    isShowDelBox.value = false;
    getData()
  };
  function changeKey() {
    searchList.value = [{
      field: null,
      operator: null,
      values: '',
      tjList: [],
      format: '',
    }]
    isHaveData.value = false
    getZd()
    getData(1)
  }
  const rowSelection = {
    onChange: (selectedRowKeys: (string | number)[], selectedRows: any[]) => {
      selectLists.value = selectedRows;
    },
  };
</script>
<style lang="less" scoped>
  .collaborationLedger {
    .info-div {
      padding: 0 24px;
      position: relative;
      width: 100%;
      background: #ffffff;
      margin-bottom: 8px;
      .info-left {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
      }

      .info-listData {
        display: flex;
        width: 100%;

        .info-item {
          width: 19%;
          height: 66px;
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          margin-right: 12px;
          display: flex;

          .info-icon {
            margin-right: 12px;
            margin-left: 8px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          }

          .info-info {
            height: 100%;
            padding: 8px 0;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .name {
              font-size: 14px;
              color: #606266;
            }

            .value {
              font-size: 20px;
              font-weight: 500;
              color: #303133;
            }
          }
        }
      }

      .info-right {
        position: absolute;
        top: 50%;
        right: 16px;
        transform: rotate(180deg) translateY(50%);
      }
    }

    .searchDiv {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      .exportBtn {
        // float: right;
        border: 1px solid #c11a20;
        width: 26%;
        height: 32px;
        text-align: center;
        line-height: 32px;
        font-size: 14px;
        font-weight: 500;
        color: #c11a20;
        cursor: pointer;
      }
    }
  }

  .my-upload {
    padding: 0 20px;
    margin-top: 32px;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .upload-click {
      font-size: 14px;
    }

    img {
      margin: 0 auto;
    }
  }

  .tips {
    margin-top: 12px;
    padding: 0 20px;

    .tipsItem {
      font-size: 12px;
      font-weight: normal;
      line-height: 20px;
      letter-spacing: -0.01px;
      color: #606266;
      display: flex;

      .downloadBtn {
        width: fit-content;
        height: 24px;
        border-radius: 4px;
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 2px 8px;
        box-sizing: border-box;
        border: 1px solid #1473dc;
        margin-left: 8px;
        font-size: 12px;
        line-height: 24px;
        color: #1473dc;

        img {
          margin-right: 5px;
        }
      }
    }
  }

  .exportBtnOfSearch {
    background-color: #c11a20;
    color: #fff !important;
    width: 20% !important;
    height: 32px !important;
  }

  .buttons {
    display: flex;
    justify-content: right;
    width: 30%;
    // float: right;
    margin-left: 20px;
    height: 100%;
    position: absolute;
    top: 0px;
    right: 20px;
  }

  .search-box {
    display: flex;
    justify-content: left;
    margin-bottom: 8px;
    //justify-content: space-between;
    //align-items: center;
  }

  :deep(.ant-select-multiple .ant-select-selector:after) {
    content: '' !important;
  }

  :deep(.ant-pagination .ant-pagination-item-active a) {
    // .ant-pagination-item {
    color: #c11a20 !important;
  }

  :deep(.ant-pagination .ant-pagination-item a) {
    color: #606266;
  }

  :deep(.ant-pagination .ant-pagination-item) {
    background-color: transparent !important;
    border: none !important;
  }

  :deep(.ant-pagination-prev) {
    border: none !important;
  }

  :deep(.ant-pagination-next) {
    border: none !important;
  }
  .myTableClass {
    padding: 10px;
    width: 100%;
    max-height: 750px;
    overflow: auto;
    box-sizing: border-box;
    .myHead {
      display: flex;
      background: #f5f7fa;
    }
    .myRow {
      display: flex;
      border-top: 1px solid #ebeef5;
      width: fit-content;
    }
    .myRow:last-child {
      border-bottom: 1px solid #ebeef5;
      width: fit-content;
    }
    .myCol {
      width: 130px;
      text-align: left;
      padding: 10px 8px;
      color: #303133;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .myCol.active {
      color: #c11a20;
    }
  }
  .footerBtn {
    float: right;
    margin: 10px 20px 20px;
  }
  .reset-btn {
    border-radius: 4px;
    &:hover {
      color: #c11a20;
      border-color: #c11a20;
    }
  }
  :deep(.pagination-container) {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 16px;

    .ant-pagination {
      margin-left: 16px;

      .ant-pagination-item {
        border: unset !important;
        height: 32px !important;
        line-height: 32px !important;

        &.ant-pagination-item-active {
          background-color: #fff !important;

          a {
            color: #c11a20 !important;
          }
        }
      }

      .ant-pagination-next,
      .ant-pagination-prev {
        height: 32px !important;
        line-height: 32px !important;
        border: unset !important;

        .ant-pagination-item-link {
          border: unset !important;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    .total-container {
      color: #606266;
      font-size: 14px;

      &>span {
        color: #c11a20;
      }
    }
  }
  .nodata{
    height: 50vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>
